package com.example.myapplication.Algorithm.getSquareRoot;

public class GetSquareRoot {
    public static void main(String[] args){
        System.out.println(binarySearch(100));
        System.out.println(newtonIteration(100));
    }

    ///二分查找
    private static int binarySearch(int x) {
        int index = -1;
        int left=0;
        int right = x;
        while (left <= right){
            int mid = left+(right-left)/2;///------l---mid---r  (mid=l+(r-l)/2)
            System.out.println("完成：left: "+left+" right: "+right);
            if(mid*mid <= x){
                index = mid;
                left = mid+1;
            }else {
                right = mid-1;
            }
        }
        return index;
    }

    ///牛顿迭代
    private static int newtonIteration(int x){
        if (x==0){
            return -1;
        }
        return (int)sqrt(x,x);
    }

    public static double sqrt(double i,int x){
        double res = (i+x/i)/2;
        if(res == i){
            System.out.println("完成：res: "+res+" i: "+i);
            return i;
        }else{
            System.out.println("继续：res: "+res+" i: "+i);
            return sqrt(res,x);
        }
    }

}
